package com.softWang.common.handler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.softWang.common.exception.ErrorCode;
import com.softWang.common.response.ResponseResult;
import com.softWang.common.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 访问一个需要认证的 URL 资源，但是此时自己尚未认证（登录）的情况下，会触发此类，返回 401 状态码，并返回错误信息。
 */
@Component
@Slf4j
@SuppressWarnings("JavadocReference") // 忽略文档引用报错
public class AuthenticationEntryPointMyImpl implements AuthenticationEntryPoint {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        log.debug("[commence][访问 URL({}) 时，没有登录]", request.getRequestURI(), e);
        String msg = "";
        try {
            msg = objectMapper.writeValueAsString(ResponseResult.failure(ErrorCode.UNAUTHORIZED));
        } catch (JsonProcessingException ex) {
            throw new RuntimeException(ex);
        }
        WebUtils.renderString(response, msg);
    }

}
